package com.hds.modules.sys.controller.base;

import com.hds.common.annotation.SysLog;
import com.hds.common.exception.RRException;
import com.hds.common.utils.*;
import com.hds.common.validator.Assert;
import com.hds.modules.app.entity.SMSCaptcha;
import com.hds.modules.app.utils.DateUtils;
import com.hds.modules.app.utils.HdsUtils;
import com.hds.modules.sys.controller.AbstractController;
import com.hds.modules.sys.entity.config.UploadFileConfig;
import com.hds.modules.sys.entity.constant.ResCode;
import com.hds.modules.sys.entity.esurer.EsurerBatchEntity;
import com.hds.modules.sys.entity.esurer.EsurerSmsRecordsEntity;
import com.hds.modules.sys.entity.esurer.EsurerUserEntity;
import com.hds.modules.sys.service.base.EsurerBatchService;
import com.hds.modules.sys.service.base.EsurerSmsRecordsService;
import com.hds.modules.sys.service.base.EsurerUserService;
import com.hds.modules.app.service.SMSCaptchaService;
import com.hds.modules.app.utils.SmsUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author guonan
 * @Email guonan@yewcn.com
 * @Description
 * @Date 2018/6/12 10:35
 */
@RestController
@RequestMapping("/sys/esurer")
public class EsurerController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SMSCaptchaService sMSCaptchaService;

    @Autowired
    EsurerUserService esurerUserService;

    @Autowired
    EsurerBatchService esurerBatchService;

    @Autowired
    EsurerSmsRecordsService esurerSmsRecordsService;

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    UploadFileConfig uploadFileConfig;

    private static final int STATUS_SUCCESS = 0;
    private static final int STATUS_FAIL = 1;



    public static String[] list2Array(List list){
        int size=list.size();
        String[] array = (String[])list.toArray(new String[size]);
        return array;
    }


    /**
     * 发送短信通知【宜安保】
     * @param mobiles 手机号
     * @return
     */
    @PostMapping("/sms/send")
    public R sendSmsNotice4Esurer(@RequestParam(value="mobiles[]") String[] mobiles) {

        String yabAppid = smsUtils.getYabAppId(); // 宜安保的appid

        int i = 0;
        long start = System.currentTimeMillis();
        for (String mobile: mobiles) {
            //根据手机号码查询该用户
            EsurerUserEntity user = esurerUserService.queryByMobile(mobile);

            List<String> params = new ArrayList<>();
            // 用户参数
            params.add(user.getUsername());
            String[] o = list2Array(params);

            EsurerSmsRecordsEntity record = new EsurerSmsRecordsEntity();
            String statusCode=null;

            Map<String, Object> map = sMSCaptchaService.getSMSNotice(mobile,yabAppid, smsUtils.getEsurerNoticeTempId(), null);
            statusCode = map.get("statusCode").toString();
            logger.info("statusCode:{}", statusCode);
            if("000000".equals(statusCode)){
                i++;
            }

            //更新短信记录表-状态码
            record.setUid(user.getId());
            record.setSendTime(new Date());
            record.setErrorCode(statusCode);

            if(SMSCaptcha.Code.SUCCESS.getCode().equals(statusCode)){
                record.setStatus(STATUS_SUCCESS);
            }else{
                record.setStatus(STATUS_FAIL);
            }
            esurerSmsRecordsService.insert(record);
        }
        long end = System.currentTimeMillis();

        return R.ok("成功发送"+ i +"条").put("耗时", (end - start) + "豪秒");

    }


    /**
     * 宜安保用户码列表
     */
    @GetMapping("/user/list")
    public R list(@RequestParam Map<String, Object> params){

        String keyword = (String)params.get("keyword");
        if(keyword!=null){
            Boolean b = NumberUtils.isNumber(keyword);
            if(b)
                params.put("mobile", keyword);
            else params.put("username", keyword);
        }

        PageUtils page = esurerUserService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 宜安保短信发送记录列表
     */
    @GetMapping("/records/list")
    public R recordsList(@RequestParam Map<String, Object> params){
        PageUtils page = esurerSmsRecordsService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 数据导入记录
     */
    @GetMapping("/import/batch")
    public R dataBatch(@RequestParam Map<String, Object> params){
        PageUtils page = esurerBatchService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 数据导入
     */
    @GetMapping("/data/import")
    @Transactional
    public R excelDateImport(String fileName){

        Assert.isNull(fileName,"请输入文件名");
        Map<String, Object> fmap = new HashMap<>();
        fmap.put("file_name", fileName);
        List<EsurerBatchEntity> batchList = esurerBatchService.selectByMap(fmap);         // 查询该文件是否导入过

        if(batchList!=null && batchList.size() > 0)
            return R.error(ResCode.YAB_FILENAME_REPEAT_IMPORT,
                ResCode.YAB_FILENAME_REPEAT_IMPORT_DESC + fileName);

        String filePath = uploadFileConfig.getFileStoragePath() + fileName;               // 该文件的绝对路径
        ReadExcelUtils excel = new ReadExcelUtils(filePath);
        int i=0,j=0;
        long start, end;
        List<String> repeatList = new ArrayList<>();                                      // 重复的数据列表[每次导入有多少条重复的数据]
        EsurerBatchEntity batch = new EsurerBatchEntity();
        start = System.currentTimeMillis();
        try{

            PoiUtils poi = new PoiUtils();
            List<List<String>> list = poi.readExcel(filePath);
            logger.info("list:{}", list);

            for (int z = 0; z < list.size(); z++) {
                List<String> listCell = list.get(z);

                String mobile = listCell.get(3);

                Map<String, Object> _map = new HashMap<>();
                _map.put("mobile", mobile);
                List<EsurerUserEntity> currUserList = esurerUserService.selectByMap(_map);  // 查询该用户是否存在

                if(currUserList!=null && currUserList.size()>0){
                    j++;
                    repeatList.add(mobile);
                    continue;
                }

                EsurerUserEntity user = new EsurerUserEntity();
                user.setUsername(listCell.get(0));
                user.setGender(listCell.get(1));
                user.setBirth(com.hds.common.utils.DateUtils.stringToDate(listCell.get(2), "yyyy-MM-dd"));
                user.setCreateTime(new Date());
                user.setMobile(mobile);

                boolean b = esurerUserService.insert(user);
                if(b)i++;

            }
            end = System.currentTimeMillis();
            batch.setCount(i);
            batch.setCreateTime(new Date());
            batch.setStatus(EsurerBatchEntity.SUCCESS);
            batch.setFileName(fileName);
            esurerBatchService.insert(batch);

        }catch(Exception e){
            System.out.println("e"+e.getMessage());
            batch.setCount(i);
            batch.setCreateTime(new Date());
            batch.setStatus(EsurerBatchEntity.FAIL);
            batch.setFileName(fileName);
            esurerBatchService.insert(batch);
            throw new RRException(e.getMessage());
        }

        return R.ok("耗时"+(end - start) + "毫秒")
                .put("导入数据条数", i)
                .put("重复的手机号数", j)
                .put("重复手机号", repeatList);
    }




}


